const tile = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8'
    })
})
const zoom = 4, center = ol.proj.fromLonLat([107.11040599933166, 34.26271532332011])
var map = new ol.Map({
    target: 'map',
    layers: [
        tile
    ],
    view: new ol.View({
        center,
        zoom
    })
});

const minWidth = 60
const dom = document.getElementById('scaleLine')
let currentZoom = -1
// 地图拖动和缩放事件
map.on('moveend', function (e) {
    if(currentZoom === map.getView().getZoom()) return
    const res = map.getView().getResolution()
    let width = minWidth;
    let minScale = res * width
    let unit = 'm', scale = minScale
    if(minScale / 1000 > 1) {
        unit = 'km'
        scale = Math.ceil(minScale / 1000)
    }
    const breaks = [1000, 500, 200, 100, 50, 20, 10]
    for (let i = 0; i < breaks.length; i++) {
        const b = breaks[i]
        if(scale / b > 1) {
            scale = Math.ceil(scale / b) * b
            break
        }
    }
    width = unit === 'm' ? scale / res : scale * 1000 / res
    dom.style.width = (width + 4) + 'px'
    dom.innerText = scale + unit
    currentZoom = map.getView().getZoom()
})